package com.incross.dawin.http.parser;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

import com.incross.dawin.objects.AdInfos;

public class BKAdInfoParser {
	public static final String ATTRIBUTE_SKIP = "skip";
	public static final String ATTRIBUTE_COMPLETE = "complete";
	public static final String ATTRIBUTE_FIRST_QUARTILE = "firstQuartile";
	public static final String ATTRIBUTE_MID_POINT = "midpoint";
	public static final String ATTRIBUTE_THIRD_QUARTILE = "thirdQuartile";
	
	private Element mXmlObject;
	
	private BasicInfoParser mBasicInfos;
	private IconInfoParser mIconInfos;
	private MediaFileInfoParser mMediaFileInfos;
	private TrackingInfoParser mTrackingInfos;
	
	
	
	public BKAdInfoParser(String xmlObject) {
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = factory.newDocumentBuilder();
			
			InputStream is = new ByteArrayInputStream(xmlObject.getBytes());
			Document doc = documentBuilder.parse(is);
			
			mXmlObject = doc.getDocumentElement();
			
			is.close();
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Extract tracking events
		mBasicInfos = new BasicInfoParser(mXmlObject);
		if(!mBasicInfos.getAdId().equals("-1")) {
			mIconInfos = new IconInfoParser(mXmlObject.getElementsByTagName("Icons"));
			mMediaFileInfos = new MediaFileInfoParser(mXmlObject.getElementsByTagName("MediaFiles"));
			mTrackingInfos = new TrackingInfoParser(mXmlObject.getElementsByTagName("TrackingEvents"));
		}
	}
	
	public AdInfos parse() {
		return new AdInfos(mBasicInfos, mTrackingInfos, mMediaFileInfos, mIconInfos);
	}

}
